package com.gxgeek.javabasic.file;

import java.io.*;

/**
 * Created by gx on 2017/7/10.
 */
public class TestFile {

    public static String encode="UTF-8";

    /**
     * 功能：Java读取txt文件的内容
     * 步骤：1：先获得文件句柄
     * 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
     * 3：读取到输入流后，需要读取生成字节流
     * 4：一行一行的输出。readline()。
     * 备注：需要考虑的是异常情况
     * @param path
     */
    public static  String readFile(String path){
        StringBuilder sb= new StringBuilder();
        File file = new File(path);
        if (!file.exists()&&!file.isFile()){
            System.out.println("文件不存在");
            return  sb.toString() ;
        }
        try {
            InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
//            inputStream.
            BufferedReader inputStreamReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

//            InputStreamReader reader = new InputStreamReader(new FileInputStream(file),encode);
//            BufferedReader bufferedReader = new BufferedReader(reader);
            String lineText = null;
            while ((lineText=inputStreamReader.readLine())!=null){
                sb.append(lineText+"\n");
//                System.out.println(lineText);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("读取失败");
            e.printStackTrace();
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        String path = "/Users/gaoxing/Desktop/code/study/javastudy/java-basic/";
        String url = path + "src/main/java/com/gxgeek/javabasic/file/TestFile.java";
        String text = readFile(url);
        System.out.println(text);
    }


}


